package la.renzhen.rtpt.config.source;

import la.renzhen.rtpt.config.ConfigurationSource;
import la.renzhen.rtpt.config.Reloadable;
import lombok.Data;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 30/05/2018 9:28 PM
 */
@Data
public class MergeConfigurationSource implements ConfigurationSource {

    List<ConfigurationSource> configurationSources;

    public MergeConfigurationSource(List<ConfigurationSource> configurationSources) {
        this.configurationSources = configurationSources;
    }

    @Override
    public Map<String, String> loadAll(String environment, String prefix) {
        return configurationSources.stream().map(s -> s.loadAll(environment, prefix))
                .reduce(new HashMap<String, String>(), (a, b) -> {
                    a.putAll(b);
                    return a;
                });
    }

    @Override
    public String get(String environment, String key) {
        return configurationSources.stream().map(s -> s.get(environment, key))
                .filter(s -> s != null).reduce(null, (a, b) -> b);
    }
}